# from rest_framework.views import APIView
# from rest_framework.response import Response
# from rest_framework_jwt.views import api_settings
# from rest_framework.generics import GenericAPIView
# from .utils import OAuthQQ
# import logging
# from .exceptions import QQException
# from .serializers import QQAuthorSerializers
# from rest_framework import status
# from .models import QQLogin
# from carts.utils import merge_cart_cookie_to_redis
# logger = logging.getLogger('django')
#
#
# # Create your views here.
# class QQAuthURLView(APIView):
#     def get(self, request):
#         state = request.query_params.get('next')
#         url = OAuthQQ()
#         login_url = url.get_qq_login_url(state)
#         return Response({'login_url': login_url})
#
#
# class QQAuthUserView(GenericAPIView):
#     serializer_class = QQAuthorSerializers
#
#     def get(self, request):
#         # 从查询字符串中取出code值
#         try:
#             code = request.query_params.get('code')
#         except Exception as e:
#             logger.error(e)
#             return Response({"message": "获取code失败"}, status=status.HTTP_400_BAD_REQUEST)
#         try:
#             # 根据code从qq服务器获取access_token值
#             access_token = OAuthQQ().get_qq_access_token(code)
#             # 根据access_token获取openid
#             openid = OAuthQQ().get_qq_openid(access_token)
#         except QQException as e:
#             logger.error(e)
#             return Response({'message': 'QQ服务器错误'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
#         # 根据openid查询用户
#         try:
#             oauth_user = QQLogin.objects.get(openid=openid)
#         except QQLogin.DoesNotExist:
#             # 用户第一次使用QQ登陆,没有查询
#             access_token_user_id = OAuthQQ().generate_user_token(openid)
#             return Response({'access_token': access_token_user_id})
#         else:
#             # 使用外键查询user数据
#             user = oauth_user.user
#             # 用户非第一次登陆 JWT状态保持
#             jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#             jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#
#             payload = jwt_payload_handler(user)
#             token = jwt_encode_handler(payload)
#             response = Response({
#                 "token": token,
#                 "user_id": user.id,
#                 "username": user.username
#             })
#             response = merge_cart_cookie_to_redis(request=request,user=user,response=response)
#             return response
#
#     def post(self, request):
#         # 获取post数据
#         # 使用序列化器校验数据
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         # 自动选择create方法或update方法
#         user = serializer.save()
#         jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#         jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#
#         payload = jwt_payload_handler(user)
#         token = jwt_encode_handler(payload)
#         response = Response({
#             "token": token,
#             "user_id": user.id,
#             "username": user.username
#         })
#         response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
#         return response
from rest_framework.views import APIView
from .utils import OAuthQQ
from rest_framework.response import Response
from .exceptions import QQAPIError
from .models import QQLogin
from rest_framework import status
from .serializers import QQAuthorSerializers
from rest_framework.generics import GenericAPIView
from rest_framework.settings import api_settings
class QQAuthURLView(APIView):
    """
    获取QQ登录的url
    """
    def get(self, request):
        """
        提供用于qq登录的url
        """
        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_qq_login_url()
        return Response({'login_url': login_url})


class QQAuthUserView(GenericAPIView):
    """
    QQ登录的用户
    """
    serializer_class = QQAuthorSerializers
    def get(self, request):
        """
        获取qq登录的用户数据
        """
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ()

        # 获取用户openid
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_openid(access_token)
        except QQAPIError:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 判断用户是否存在
        try:
            qq_user = QQLogin.objects.get(openid=openid)
        except QQLogin.DoesNotExist:
            # 用户第一次使用QQ登录
            token = oauth.generate_save_user_token(openid)
            return Response({'access_token': token})
        else:
            # 找到用户, 生成token
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response

    def post(self, request):
        """
        保存QQ登录用户数据
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 生成已登录的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })

        return response